package com.lanren.familybookapp.helper.upgrade;

import android.app.Activity;
import android.os.Environment;
import android.view.View;

import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.lanren.common.app.ApiUrl;
import com.lanren.common.http.HttpManager;
import com.lanren.common.utils.AppUtils;
import com.lanren.common.utils.FileUtils;
import com.lanren.common.widget.NumberProgressBar;
import com.lanren.easydialog.DialogViewHolder;
import com.lanren.easydialog.EasyDialog;
import com.lanren.easyhttp.callback.DownloadProgressCallBack;
import com.lanren.easyhttp.callback.SimpleCallBack;
import com.lanren.easyhttp.exception.ApiException;
import com.lanren.familybookapp.R;
import com.lanren.familybookapp.app.MyApplication;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;

/**
 * @ClassName AppUpgradeHelp
 * @Description TODO
 * @Author chongheng.wang
 * @Date 2020/3/8 16:55
 * @Version 1.0
 */
public class AppUpgradeHelp implements IAppUpgradeView.AppUpgradeModel {

    private IAppUpgradeView.AppUpgradeModel appUpgradeModel;
    private IAppUpgradeView.AppUpgradeView upgradeView;
    private NumberProgressBar numberProgressBar;
    private EasyDialog easyDialog;
    private Activity context;

    private AppUpgradeHelp() {
        appUpgradeModel = this;
    }

    private static class SingletonHolder {
        private final static AppUpgradeHelp instance = new AppUpgradeHelp();
    }

    public static AppUpgradeHelp getInstance() {
        return SingletonHolder.instance;
    }

    @Override
    public void onSuccess(AppUpgradeBean data) {
        showUpgradeDialog(data);
    }

    @Override
    public void onDownLoadSuccess(int upgradeNum, boolean done) {
        if (numberProgressBar != null) {
            numberProgressBar.setProgress(upgradeNum);
        }
    }

    @Override
    public void onDownLoadStart() {
        if (numberProgressBar != null) {
            numberProgressBar.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onDownLoadComplete(String path) {
        if (XXPermissions.isHasPermission(context, Permission.REQUEST_INSTALL_PACKAGES)) {
            AppUtils.installApk(context, path, MyApplication.getApplication().getPackageName() + ".lanren");
            clossDataAndView();
        } else {
            requestPermission(path);
        }
    }

    public void checkVersion(Activity context, final String appVersion, final IAppUpgradeView.AppUpgradeView upgradeView) {
        this.context = context;
        this.upgradeView = upgradeView;

        Map<String, String> map = new LinkedHashMap<>();
        map.put("appVersion", appVersion);
        HttpManager.post(ApiUrl.API.BOOK_APP_CHECK)
                .params(map)
                .execute(new SimpleCallBack<AppUpgradeBean>() {
                    @Override
                    public void onError(ApiException e) {
                        upgradeView.showError(e.getCode(), e.getMessage());
                        clossDataAndView();
                    }

                    @Override
                    public void onSuccess(AppUpgradeBean appUpgradeBean) {
                        appUpgradeModel.onSuccess(appUpgradeBean);
                    }
                });
    }

    private boolean isUpgrade = true;

    private void showUpgradeDialog(final AppUpgradeBean data) {
        if (easyDialog == null) {
            easyDialog = new EasyDialog(context, R.layout.dialog_update) {
                @Override
                public void onBindViewHolder(final DialogViewHolder holder) {
                    holder.setText(R.id.tv_dialog_update_name, "版本号:" + data.getAppVersion());
                    holder.setText(R.id.tv_dialog_update_size, "大小:" + data.getSize() + "m");
                    holder.setText(R.id.tv_dialog_update_content, data.getUpgradeContent());
                    numberProgressBar = holder.getView(R.id.pb_dialog_update_progress);
                    holder.setOnClick(R.id.tv_dialog_update_update, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (isUpgrade) {
                                isUpgrade = false;
                                getAppApk(data.getApkUri());
                                holder.setText(R.id.tv_dialog_update_update, "正在升级中...");
                            }
                        }
                    }).setOnClick(R.id.iv_dialog_update_close, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (disposable != null) {
                                disposable.dispose();
                            }
                            clossDataAndView();
                        }
                    });
                }
            }.setCancelAble(false).setCanceledOnTouchOutside(false).showDialog(true);
        } else {
            easyDialog.showDialog(true);
        }

    }

    Disposable disposable = null;

    public void getAppApk(String appUri) {
        disposable = HttpManager.downloadRequest(appUri)
                .savePath(Environment.getExternalStorageDirectory() + "/family/")
                .saveName(FileUtils.getPathFileName(appUri))
                .execute(new DownloadProgressCallBack<String>() {
                    @Override
                    public void onStart() {
                        appUpgradeModel.onDownLoadStart();
                    }

                    @Override
                    public void onError(ApiException e) {
                        upgradeView.showError(e.getCode(), e.getMessage());
                    }

                    @Override
                    public void update(long l, long l1, boolean b) {
                        int progress = (int) (l * 100 / l1);
                        appUpgradeModel.onDownLoadSuccess(progress, b);
                    }

                    @Override
                    public void onComplete(String s) {
                        appUpgradeModel.onDownLoadComplete(s);
                    }
                });
    }


    private void requestPermission(final String path) {

        XXPermissions.with(context)
                // 可设置被拒绝后继续申请，直到用户授权或者永久拒绝
                //.constantRequest()
                // 支持请求6.0悬浮窗权限8.0请求安装权限
                //.permission(Permission.REQUEST_INSTALL_PACKAGES)
                // 不指定权限则自动获取清单中的危险权限
                .permission(Permission.REQUEST_INSTALL_PACKAGES)
                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        if (isAll) {
//                            ToastUtils.show("获取权限成功");
                        } else {
                            ToastUtils.show("获取权限成功，部分权限未正常授予");
                        }
                        if (easyDialog != null) {
                            easyDialog.dismiss();
                            easyDialog = null;
                        }
                        showUpgradeConfirmDialog(path);
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        if (quick) {
                            ToastUtils.show("被永久拒绝授权，请手动授予权限");
                            //如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.gotoPermissionSettings(context);
                        } else {
                            ToastUtils.show("获取权限失败");
                            isHasPermission(path);
                        }
                    }
                });
    }

    private void isHasPermission(String path) {
        if (XXPermissions.isHasPermission(context, Permission.REQUEST_INSTALL_PACKAGES)) {
            ToastUtils.show("已经获取到权限，不需要再次申请了");
        } else {
            requestPermission(path);
            ToastUtils.show("还没有获取到安装权限");
        }
    }

    private void showUpgradeConfirmDialog(final String path) {
        new EasyDialog(context, R.layout.dialog_message) {
            @Override
            public void onBindViewHolder(DialogViewHolder holder) {
                holder.setText(R.id.tv_dialog_message_title, "提示");
                holder.setText(R.id.tv_dialog_message_message, "已经获取到安装权限是否继续升级");
                holder.getView(R.id.tv_dialog_message_confirm).setBackgroundResource(R.drawable.dialog_message_button);
                holder.setOnClick(R.id.tv_dialog_message_cancel, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        clossDataAndView();
                        dismiss();
                    }
                }).setOnClick(R.id.tv_dialog_message_confirm, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AppUtils.installApk(context, path, MyApplication.getApplication().getPackageName() + ".lanren");
                        clossDataAndView();
                        dismiss();
                    }
                });
            }
        }.backgroundLight(0.2)
                .setCancelAble(false)
                .setCanceledOnTouchOutside(false)
                .showDialog(true);
    }

    public void clossDataAndView() {
        if (easyDialog != null) {
            easyDialog.dismiss();
            easyDialog = null;
        }
        if (numberProgressBar != null) {
            numberProgressBar = null;
        }
        if (upgradeView != null) {
            upgradeView = null;
        }
        if (context != null) {
            context = null;
        }

        isUpgrade = true;
    }


}
